package org.dandelion.memo.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.navigation.NavigationView;

import org.dandelion.R;
import org.dandelion.memo.adapter.MemoAdapter;
import org.dandelion.memo.dao.DBHelper;
import org.dandelion.memo.dao.MemoDao;
import org.dandelion.memo.entity.Memo;
import org.dandelion.memo.entity.MemoCategory;

import java.util.ArrayList;
import java.util.List;

public class MemoActivity extends BaseActivity {
    public static final String TAG = "MemoActivity";

    private DrawerLayout drawerLayout;
    private ListView listView;
    private Toolbar toolbar;
    private FloatingActionButton addMemoBtn;
    private NavigationView navView;

    private final List<Memo> memoList = new ArrayList<>();
    private final List<MemoCategory> memoCategoryList = new ArrayList<>();
    private MemoAdapter memoAdapter;

    private final MemoDao memoDao = MemoDao.getInstance();
    private DBHelper dbHelper;

    private Status status = Status.ALL;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_memo);
        findView();

        setSupportActionBar(toolbar);
        initNavView();

        dbHelper = new DBHelper(this, "toolbox", null, 1);

        toolbar.setOnClickListener(view -> drawerLayout.openDrawer(GravityCompat.START));


        addMemoBtn.setOnClickListener(view -> {
            Intent intent = new Intent(this, AddMemoActivity.class);
            startActivity(intent);
        });

        listView.setMultiChoiceModeListener(new MultiChoiceModeListener(listView));

        listView.setOnItemClickListener((parent, view, position, id) -> {
            Memo memo = memoList.get(position);
            Intent intent = new Intent(this, AddMemoActivity.class);
            intent.putExtra("memo", memo);
            startActivity(intent);
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        refreshMemoList();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dbHelper.close();
    }

    void findView() {
        drawerLayout = findViewById(R.id.drawer_layout);
        toolbar = findViewById(R.id.toolbar);
        listView = findViewById(R.id.list_view);
        navView = findViewById(R.id.nav_view);
        addMemoBtn = findViewById(R.id.btn_add_memo);
    }

    void initNavView() {
        navView.setItemIconTintList(null);
        navView.setNavigationItemSelectedListener(item -> {
            int id = item.getItemId();

            if (id == R.id.memo_nav_all) {
                if (status != Status.ALL) {
                    status = Status.ALL;
                    refreshMemoList();
                }

            } else if (id == R.id.memo_nav_collect) {
                if (status != Status.COLLECT) {
                    status = Status.COLLECT;
                    refreshMemoList();
                }

            } else if (id == R.id.memo_nav_deleted) {
                if (status != Status.DELETED) {
                    status = Status.DELETED;
                    refreshMemoList();
                }
            }

            drawerLayout.closeDrawers();
            updateToolBarTitle();

            return true;
        });
    }

    void updateToolBarTitle() {
        if (status == Status.ALL) {
            toolbar.setTitle("所有笔记");
        } else if (status == Status.COLLECT) {
            toolbar.setTitle("我的收藏");
        } else if (status == Status.DELETED) {
            toolbar.setTitle("已经删除");
        }
    }

    void refreshMemoList() {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        memoList.clear();

        switch (status) {
            case ALL:
                memoList.addAll(memoDao.findUndeleted(db));
                break;
            case COLLECT:
                memoList.addAll(memoDao.findCollect(db));
                break;
            case DELETED:
                memoList.addAll(memoDao.findDeleted(db));
                break;
        }

        if (listView.getAdapter() == null) {
            memoAdapter = new MemoAdapter(this, R.layout.memo_item, memoList);
            listView.setAdapter(memoAdapter);
        } else {
            memoAdapter.notifyDataSetChanged();
        }
    }

    public Status getStatus() {
        return status;
    }

    enum Status {
        ALL,
        COLLECT,
        DELETED
    }

    private class MultiChoiceModeListener implements AbsListView.MultiChoiceModeListener {
        private final ListView mListView;
        private TextView mTitleTextView;
        private final List<Memo> mSelectedItems = new ArrayList<>();

        private MultiChoiceModeListener(ListView listView) {
            mListView = listView;
        }

        @Override
        public void onItemCheckedStateChanged(ActionMode mode, int position, long id,
                                              boolean checked) {
            mSelectedItems.add(memoAdapter.getItem(position));
            mTitleTextView.setText(("已选择 " + mListView.getCheckedItemCount() + " 项"));
            memoAdapter.notifyDataSetChanged();
        }

        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            mode.getMenuInflater().inflate(R.menu.check_task, menu);

            @SuppressLint("InflateParams")
            View multiSelectActionBarView = LayoutInflater.from(MemoActivity.this)
                    .inflate(R.layout.action_mode_bar, null);

            mode.setCustomView(multiSelectActionBarView);
            mTitleTextView = multiSelectActionBarView.findViewById(R.id.title);
            mTitleTextView.setText("已选择 0 项");

            MenuItem item = mode.getMenu().findItem(R.id.ok);

            Status status = getStatus();

            if (status == Status.ALL) {
                item.setTitle("删除");
            } else if (status == Status.DELETED) {
                item.setTitle("还原");
            } else if (status == Status.COLLECT) {
                item.setTitle("取消收藏");
            }

            memoAdapter.setCheckable(true);
            memoAdapter.notifyDataSetChanged();
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false;
        }

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            final int id = item.getItemId();

            switch (status) {
                case ALL:
                    if (id == R.id.ok) {
                        for (Memo selectedItem : mSelectedItems) {
                            // 标记为删除
                            selectedItem.setDeleted(true);
                            memoDao.update(selectedItem, dbHelper.getWritableDatabase());
                            memoList.remove(selectedItem);
                        }
                    }
                    break;

                case DELETED:
                    if (id == R.id.ok) {
                        for (Memo selectedItem : mSelectedItems) {
                            // 取消删除
                            selectedItem.setDeleted(false);
                            memoDao.update(selectedItem, dbHelper.getWritableDatabase());
                            memoList.remove(selectedItem);
                        }
                        break;
                    }

                case COLLECT:
                    if (id == R.id.ok) {
                        for (Memo selectedItem : mSelectedItems) {
                            // 取消收藏
                            selectedItem.setFavourite(false);
                            memoDao.update(selectedItem, dbHelper.getWritableDatabase());
                            memoList.remove(selectedItem);
                        }
                    }
                    break;
            }

            memoAdapter.notifyDataSetChanged();
            mode.finish();
            return true;
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {
            mSelectedItems.clear();
            memoAdapter.setCheckable(false);
            memoAdapter.notifyDataSetChanged();
        }
    }
}
